#!/bin/bash

runCommand()
{
    if [ "$1" == "mpirun" ]; then sol="$4"; else sol="$1"; fi
    sol=$(basename -- "$sol")
    sol="${sol%.*}"
    if [ -f log."$sol" ]; then rm log."$sol"; fi
    "$@" 1> >(tee -a log."$sol") 2> >(tee -a log."$sol" >&2)
    err=$?
    if [ ! $err -eq 0 ]; then exit $err; fi
}

%{%(MeshUtility%)
%:gmsh
runCommand '%(GmshSettings/Executable%)' - "gmsh/%(Name%)_Geometry.geo"

%}
%{%(FoamRuntime%)
%:BlueCFD
%:default
# Unset and source bashrc
if [ -f "%(TranslatedFoamPath%)/etc/config/unset.sh" ]; then  # for OF < 4
   source "%(TranslatedFoamPath%)/etc/config/unset.sh" 2> /dev/null
else
   source "%(TranslatedFoamPath%)/etc/config.sh/unset" 2> /dev/null
fi
source "%(TranslatedFoamPath%)/etc/bashrc"

%}
%{%(MeshUtility%)
%:cfMesh
# Extract feature edges
runCommand surfaceFeatureEdges -angle 60 "constant/triSurface/%(Name%)_Geometry.stl" "%(Name%)_Geometry.fms"
runCommand cartesianMesh
%:snappyHexMesh
runCommand blockMesh
runCommand surfaceFeatureExtract

%{%(SnappySettings/ParallelMesh%)
%:True
runCommand decomposePar
runCommand mpirun -np %(SnappySettings/NumberCores%) snappyHexMesh -overwrite -parallel
runCommand reconstructParMesh -constant
%:False
runCommand snappyHexMesh -overwrite
%}

runCommand surfaceToPatch "constant/triSurface/%(Name%)_Geometry.stl"
%:gmsh
runCommand gmshToFoam "gmsh/%(Name%)_Geometry.msh"
runCommand transformPoints -scale "(0.001 0.001 0.001)"

%}
%{%(TwoDSettings/ConvertTo2D%)
%:True
runCommand changeDictionary
runCommand extrudeMesh
runCommand flattenMesh

%}

if [ ! -z $FOAM_API ] && [ $FOAM_API -ge 1906 ]
then
    runCommand surfaceMeshExtract mesh_outside.stl
else
    runCommand surfaceMeshTriangulate mesh_outside.stl
fi

runCommand surfaceTransformPoints -scale "(1000 1000 1000)" mesh_outside.stl mesh_outside.stl
